package org.example.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.example.model.vo.UserVo;
import org.example.util.JwtUtils;
import org.example.util.Result;
import org.example.util.UserThreadLocal;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(request.getMethod().equals(RequestMethod.OPTIONS.name()))
        {
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Headers","*");
            response.setHeader("Access-Control-Allow-Methods","*");
            response.setHeader("Access-Control-Allow-Credentials","true");
            response.setHeader("Access-Control-Max-Age","3600");
            response.setStatus(HttpStatus.OK.value());
            return true;
        }

        String token = request.getHeader("token");
        Result UserToken = JwtUtils.getUserInfo(token);
        if(request.getHeader("token")==null||!UserToken.getCode().equals(200)){
            log.info(request.getRequestURL().toString());
            response.sendRedirect(request.getContextPath()+"/interceptor/403.html");
            return false;
        }
        Map<String, Object> map = JwtUtils.getUserInfo(request.getHeader("token")).getData();
        UserVo user = (UserVo)map.get("user");
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        if(ex!=null)log.error(ex.getMessage());
        UserThreadLocal.remove();

    }
}
